package 优先级队列_堆;

import java.util.*;

public class 查找和最小的K对数字 {
    class Pair  {
        int u;
        int v;

        public Pair(int u, int v) {
            this.u = u;
            this.v = v;
        }
    }
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        Queue<Pair> queue = new PriorityQueue<>(new Comparator<Pair>() {
            @Override
            public int compare(Pair o1, Pair o2) {
                return (o2.u + o2.v) - (o1.u + o1.v);
            }
        });
        //按顺序排列的两个递增数组，所以可以优化双循环
        for (int i = 0; i < Math.min(nums1.length , k); i++) {
            for (int j = 0; j < Math.min(nums2.length , k); j++) {
                if (queue.size() < k){
                    queue.offer(new Pair(nums1[i] , nums2[j]));
                }else {
                    Pair curPair = queue.peek();
                    if (nums1[i] + nums2[j] > (curPair.u + curPair.v)){
                        continue;
                    }else {
                        queue.poll();
                        queue.offer(new Pair(nums1[i] , nums2[j]));
                    }
                }
            }
        }
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < k && (!queue.isEmpty()); i++) {
            List<Integer> curList = new ArrayList<>();
            Pair curPair = queue.poll();
            curList.add(curPair.u);
            curList.add(curPair.v);
            list.add(curList);
        }
        return list;
    }
}
